package main

import (
	"fmt"
	"math/rand"
	"strconv"
	"strings"
	"time"

	"github.com/xuri/excelize/v2"
)

const randomStart = 10800
const randomLast = 28800

//获取随机数
func getRandom(s int64) int64 {
	return rand.Int63n(s)
}

//获取开始时间
func getStartTime(i int64) time.Time {
	startMeeting := time.Date(2023, 6, 22, 8, 47, 0, 0, time.UTC)
	s := strconv.FormatInt(i, 10) + "s"
	afterS, _ := time.ParseDuration(s)
	return startMeeting.Add(afterS)
}

//格式化持续时间
func formatLast(i string) string {
	i = strings.Replace(i, "h", ":", 1)
	i = strings.Replace(i, "m", ":", 1)
	return strings.Replace(i, "s", "", 1)
}

//生成会议记录，包含：登录时间，退出时间，持续时间
func getMeeting() []string {
	var row = make([]string, 3)
	//login start
	endMeeting := time.Date(2023, 6, 22, 17, 15, 0, 0, time.UTC)
	st := getRandom(randomStart)
	dst := getStartTime(st)

	//last must > 2h
	var last int64
	var afterS time.Duration
	var tmp time.Time
	for {
		last = getRandom(randomLast)
		s := strconv.FormatInt(last, 10) + "s"
		afterS, _ = time.ParseDuration(s)
		tmp = dst.Add(afterS)

		if last > 9144 && tmp.Before(endMeeting) {
			break
		}
	}

	//format last
	fl := formatLast(afterS.String())
	// fmt.Println(dst.Format("2006-01-02 15:04:05"), tmp.Format("2006-01-02 15:04:05"), fl)
	row = append(row, dst.Format("2006-01-02 15:04:05"))
	row = append(row, tmp.Format("2006-01-02 15:04:05"))
	row = append(row, fl)
	return row
	// formattedTime := time.Unix(rand.Int63n(28800)+start.Unix(), 0).Format("2006-01-02 15:04:05")
	// fmt.Println(start.Format(time.RFC3339), formattedTime)
}

func writeExcel(fileName, sheetName string, table [][]string) {
	// func writeExcel(title []string, dataMap map[string]string) {
	var flag = make(chan bool, 100)
	newFile := excelize.NewFile() // 创建一个excel文件句柄
	// _ = newFile.SetCellValue("Sheet1", "A1", title[0]) //写入表头
	// _ = newFile.SetCellValue("Sheet1", "B1", title[1])
	// _ = newFile.SetSheetRow("Sheet1", "A2", &table) //写入内容
	line := 1
	for _, v := range table {
		line++
		go func(line int, v []string) { // 数据量小可以不使用goroutine
			_ = newFile.SetSheetRow(sheetName, "A"+strconv.Itoa(line), &v)
			flag <- true
		}(line, v)
		<-flag
	}
	_ = newFile.SaveAs(fileName + ".xlsx") //保存成excel
}

func readExcel(fileName, sheetName string) [][]string {
	file, err := excelize.OpenFile(fileName) //打开excel并生成句柄
	defer func() {
		_ = file.Close()
	}()
	if err != nil {
		panic(err)
	}
	codes, _ := file.GetRows(sheetName) //读取整个Sheet1表,返回的是一个string类型的二维切片格式

	//print table

	for index, row := range codes { //row即是每一行的数据
		fmt.Println(index, row)
		for i, colCell := range row { //colCell即是每一个单元格的数据
			fmt.Println(i, colCell)
		}
	}

	return codes
}

func main() {
	//获取会议表格
	table := readExcel("excelName.xlsx", "sheet1")

	//添加会议时间
	for k, v := range table {
		// table[k][0] = reName(v[0])
		table[k] = append(v, getMeeting()...)
		// fmt.Println(k, v)
	}

	//写表格测试
	//将table 写入 newFile.xlsx
	writeExcel("newFile", "Sheet1", table)

}
